package com.personal.system.controller.sys;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.personal.common.result.Result;
import com.personal.common.utils.MD5;
import com.personal.model.system.SysUser;
import com.personal.model.vo.SysUserQueryVo;
import com.personal.system.config.ThreadPoolConfig;
import com.personal.system.service.sys.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author personal
 * @since 2022-09-28
 */
@Slf4j
@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/admin/system/sysUser")
public class SysUserController {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private ThreadPoolConfig poolConfig;

    @ApiOperation("更改用户状态")
    @GetMapping("updateStatus/{id}/{status}")
    public Result updateStatus(@PathVariable String id,
                               @PathVariable Integer status) {
        sysUserService.updateStatus(id, status);
        return Result.ok();
    }

    @ApiOperation("用户列表")
    @GetMapping("/{page}/{limit}")
    public Result list(@PathVariable Long page,
                       @PathVariable Long limit,
                       SysUserQueryVo sysUserQueryVo) throws Exception {
        log.info("用户列表Controller~~~");
        //创建page对象
        Page<SysUser> pageParam = new Page<>(page, limit);

        CompletableFuture<IPage<SysUser>> future = CompletableFuture.supplyAsync(() -> {
            IPage<SysUser> pageModel = sysUserService.selectPage(pageParam, sysUserQueryVo);
            return pageModel;
        }, poolConfig.asyncExecutor());

        return Result.ok(future.join());
    }

    @ApiOperation("导出用户")
    @GetMapping("/exportList")
    public void exportList(SysUserQueryVo sysUserQueryVo, HttpServletResponse response) {
        try {
            List<SysUser> list = sysUserService.selectList(sysUserQueryVo);

            ExportParams params = new ExportParams("用户信息", "列表");

            Workbook sheets = ExcelExportUtil.exportExcel(params, SysUser.class, list);
            response.reset();
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment; filename=userList.xlsx");
            response.setContentType("application/vnd.ms-excel; charset=UTF-8");
            sheets.write(response.getOutputStream());
            sheets.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation("导入用户")
    @PostMapping("/importList")
    public boolean importList(@RequestParam("file") MultipartFile file) throws Exception {
        InputStream in = file.getInputStream();
        ImportParams params = new ImportParams();
        params.setNeedVerify(true);
        params.setTitleRows(1);
        params.setHeadRows(1);
        ExcelImportResult<SysUser> result = ExcelImportUtil.importExcelMore(in, SysUser.class, params);
        List<SysUser> list = result.getList();

        return sysUserService.saveBatch(list);
    }

    @ApiOperation("添加用户")
    @PostMapping("save")
    public Result save(@RequestBody SysUser user) {
        //把输入密码进行加密 MD5
        String encrypt = MD5.encrypt(user.getPassword());
        user.setPassword(encrypt);
        boolean is_Success = sysUserService.save(user);
        if (is_Success) {
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    @ApiOperation("根据id查询")
    @GetMapping("getUser/{id}")
    public Result getUser(@PathVariable String id) {
        SysUser user = sysUserService.getById(id);
        return Result.ok(user);
    }

    @ApiOperation("修改用户")
    @PostMapping("update")
    public Result update(@RequestBody SysUser user) {
        boolean is_Success = sysUserService.updateById(user);
        if (is_Success) {
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    @ApiOperation("删除用户")
    @DeleteMapping("remove/{id}")
    public Result remove(@PathVariable String id) {
        boolean is_Success = sysUserService.removeById(id);
        if (is_Success) {
            return Result.ok();
        } else {
            return Result.fail();
        }
    }
}

